<?php
/**
 * Created by PhpStorm.
 * User: mac1
 * Date: 16/6/10
 * Time: 上午10:32
 */

namespace app\admin\controller;
use app\admin\model\Admintype;
use app\admin\model\Campus;
use app\admin\validate\AdminValidate;
use app\admin\validate\Admin2Validate;
use think\Db;
use app\admin\model\Admin;

class AdminController extends CommonController
{
    /**
     * 账号密码登录
     * @return bool
     */
    public  function studentLogin(){
        $phone = $_POST['phone'];
        $pass = $_POST['pass'];
        if(preg_match("/^1[34578]\d{9}$/", $phone)){
            if(empty($pass) || !isset($pass)){
                return json(['status'=>2,'msg'=>'请填写正确的密码']);
            }else{
                $username = Db::table('ew_admin')->where('username',$phone)->find();
                if(empty($username)){
                    return json(['status'=>3,'msg'=>'没有此用户']);
                }else{
                    if($username['password'] != $pass){
                        return json(['status'=>4,'msg'=>'密码错误']);
                    }else{
                        return json(['status'=>5,'msg'=>'成功登陆']);
                    }
                }
            }
        }else{
            return json(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }

    }

    /**
     * 手机验证码登录
     * @return bool
     */
    /**
     * 手机登录或注册时发送的验证码
     * @return bool
     * 参数：phone type(1是老手机发送 2是新手机发送)
     * 返回值：0参数错误，1手机格式错误，21登录无此号，22注册有此号，3验证码发送失败，4返回md5加密验证码
     */
    public  function getPhoneCode(){
        $admin = Db::table('ew_user')->where('user_id', session('loginSession')['user_id'])->find();
        $num = rand(100000,999999);
        $output = $this->duanxin($admin['user_phone'],2,$num);
        $output = explode("\n",$output);
        $one = count($output);
        if($one == 3){
            $code = array();
            $code['user_code'] = md5($num);
            $code['user_codetime'] = time();
            $code['user_codestatus'] = 1;
            $res = Db::table('ew_user')->where('user_id',$admin['user_id'])->update($code);
            if($res){
                return json_encode(['status'=>200,'msg'=>md5($num)]);
            }else{
                return json_encode(['status'=>0,'msg'=>'操作失败，请联系管理员']);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>'短信发送失败，请联系管理员']);
        }

    }

    public  function getLoginPhoneCode(){
        $phone = $_POST['phone'];
        $user = Db::table('ew_user')->where('user_phone', $phone)->find();
        if(empty($user)){
            return json_encode(['status'=>0,'msg'=>'无此手机号码用户']);
        }
        if($user['user_status'] == 2){
            return json_encode(['status'=>0,'msg'=>'账户被冻结，请联系管理员']);
        }
        $num = rand(100000,999999);
        $output = $this->duanxin($phone,2,$num);
        $output = explode("\n",$output);
        $one = count($output);
        if($one == 3){
            $code = array();
            $code['user_code'] = md5($num);
            $code['user_codetime'] = time();
            $code['user_codestatus'] = 1;
            $res = Db::table('ew_user')->where('user_phone', $phone)->update($code);
            if($res){
                return json_encode(['status'=>200,'msg'=>md5($num)]);
            }else{
                return json_encode(['status'=>0,'msg'=>'操作失败，请联系管理员']);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>'短信发送失败，请联系管理员']);
        }

    }
    //=============================================================================
    public  function getRegPhoneCode(){
        $phone = $_POST['phone'];
        $user = Db::table('ew_user')->where('user_phone', $phone)->find();
        if(!empty($user)){
            return json_encode(['status'=>0,'msg'=>'已经有此手机号码用户']);
        }
        $num = rand(100000,999999);
        $output = $this->duanxin($phone,2,$num);
        $output = explode("\n",$output);
        $one = count($output);
        if($one == 3){
            $code = array();
            $code['code'] = md5($num);
            $code['time'] = time();
            $code['phone'] = $phone;
            $res = Db::table('ew_phonecode')->where('phone', $phone)->find();
            if($res){
                $res3=Db::table('ew_phonecode')->where('phone', $phone)->update($code);
                if($res3){
                    return json_encode(['status'=>200,'msg'=>'ok']);
                }else{
                    return json_encode(['status'=>0,'msg'=>'更新已有数据失败，联系管理员']);
                }
            }else{
                $res4 = Db::table('ew_phonecode')->insert($code);
                if($res4){
                    return json_encode(['status'=>200,'msg'=>'ok']);
                }else{
                    return json_encode(['status'=>0,'msg'=>'保存数据失败，联系管理员']);
                }
            }
        }else{
            return json_encode(['status'=>0,'msg'=>'短信发送失败，请联系管理员']);
        }

    }
    public function newUser()
    {
        $code = md5($_POST['usercode']);
        unset($_POST['usercode']);
        $validata = new AdminValidate();
        if (!$validata->check($_POST)) {
            $returnData['status'] = 0;
            $returnData['msg'] = $validata->getError();
            return json_encode($returnData);
        } else {
            $_POST['user_createtime'] = date("Y-m-d H:i:s");
            $_POST['user_updatetime'] = date("Y-m-d H:i:s");
            $_POST['user_password'] = md5($_POST['user_password']);
            $_POST['user_dealpass'] = md5($_POST['user_dealpass']);
            $ishave = Db::table('ew_user')->where('user_username',$_POST['user_username'])->find();
            $ishave2 = Db::table('ew_user')->where('user_phone',$_POST['user_phone'])->find();
            if(!empty($ishave)){
                $returnData['status'] = 0;
                $returnData['msg'] = "已经有此用户名了";
                return json_encode($returnData);
            }
            if(!empty($ishave2)){
                $returnData['status'] = 0;
                $returnData['msg'] = "已经有此手机号了";
                return json_encode($returnData);
            }
            $res3 = Db::table('ew_phonecode')->where('phone', $_POST['user_phone'])->find();
            if(empty($res3)){
                return json_encode(['status'=>0,'msg'=>'请输入原来的号码']);
            }
            //=====================================
            if($code != $res3['code']){
                return json_encode(['status'=>0,'msg'=>'验证码错误']);
            }
            $now = time();
            if($now - $res3['time'] >= 601){
                return json_encode(['status'=>0,'msg'=>'验证码超时']);
            }
            //=====================================
            $res = Db::table('ew_user')->insert($_POST);
            if($res){
                $returnData['status'] = 200;
                $returnData['msg'] = "成功";
                return json_encode($returnData);
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "保存失败";
                return json_encode($returnData);
            }

        }
    }
    //===================================================================


    public function authLogin()
    {
        $username = input('UserName');
        $password = input('PassWord');
        if (isNotNull($username) && isNotNull($password)) {
            $admin = Db::table('ew_user')->where(["user_username" => $username,'user_status'=>1])->find();
            if ($admin) {
                if($admin['user_password'] == md5($password)){
                    session('loginSession', $admin);
                    return 1;
                }else{
                    session("loginSession", null);
                    return 0;
                }
            } else {
                session("loginSession", null);
                return 0;
            }
        } else {
            return 0;
        }
    }
    /**
     * 退出
     */
    public function authLogout()
    {
        session("loginSession", null);
        return 1;
    }

    /**
     * 个人信息
     */
    public function personinfo_manage()
    {
        $admin = Db::table('ew_admin')->where('id', session('loginSession')['id'])->find();
        $this->assign('admin', $admin);
        return $this->fetch('admin/personinfo');
    }

    /**
     * 修改个人信息
     */
    public function personal_setting()
    {
        $admin = Db::table('ew_user')->where('user_id', session('loginSession')['user_id'])->find();
        $admin['user_createtime'] = substr($admin['user_createtime'], 0, 10);
        $this->assign('admin', $admin);
        return $this->fetch('admin/setting');
    }

    public function updateSetting()
    {
        $id = $_POST['id'];
        unset($_POST['id']);
//        $dir = $_SERVER['DOCUMENT_ROOT'];
//        $url =  "http://".$_SERVER['HTTP_HOST'];
//        $data = array();
//        $validata = new Admin2Validate();
//        if (!$validata->check($_POST)) {
//            $returnData['status'] = 0;
//            $returnData['msg'] = $validata->getError();
//            return json_encode($returnData);
//        }
//        if(!empty($_FILES['pic']['tmp_name'])){
//            if(move_uploaded_file($_FILES['pic']['tmp_name'],"{$dir}/nanyi/avatar/{$_FILES['pic']['name']}")){
//                $data['user_avatar'] = "{$url}/nanyi/avatar/{$_FILES['pic']['name']}";
//            }else{
//                return json_encode(['status'=>0,'msg'=>'图片保存失败']);
//            }
//        }
        $ishave = Db::table('ew_user')->where('user_id',$id)->find();
        $name = $_POST['user_username'];
        if($ishave['user_username'] != $name){
            $howm = Db::table('ew_user')->where('user_username',$name)->count();
            if($howm >= 1){
                return json_encode(['status'=>0,'msg'=>'用户名重复，请重新输入']);
            }
        }
        $phone = $_POST['user_phone'];
        if($ishave['user_phone'] != $phone){
            $howm = Db::table('ew_user')->where('user_phone',$phone)->count();
            if($howm >= 1){
                return json_encode(['status'=>0,'msg'=>'手机号重复，请重新输入']);
            }
        }
        $_POST['user_updatetime'] = date("Y-m-d H:i:s");
        if(isset($_POST['user_password'])){
            $password = $_POST['user_password'];
            if($password == ''){
                unset($password);
            }else{
                if(strlen($password) < 6){
                    return json_encode(['status'=>0,'msg'=>'密码长度不能低于6位']);
                }else{
                    $_POST['user_password'] = md5($password);
                }
            }
        }

        $res = Db::table('ew_user')->where('user_id',$id)->update($_POST);
        if($res){
            $returnData['status'] = 1;
            $returnData['msg'] = "成功";
            return json_encode($returnData);
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = "修改失败";
            return json_encode($returnData);
        }
    }

    /**
     * 修改密码
     */
    public function change_password()
    {
        return $this->fetch('admin/password');
    }

    public function updatePassword()
    {
        $admin = Db::table('ew_user')->where('user_id', session('loginSession')['user_id'])->find();
        if (md5($_POST['oldPassword']) != $admin['user_password']) {
            $returnData['status'] = 0;
            $returnData['msg'] = '原密码输入不正确';
            return json_encode($returnData);
        } else if ($_POST['password'] != $_POST['surePassword']) {
            $returnData['status'] = 0;
            $returnData['msg'] = '两次密码输入不一样';
            return json_encode($returnData);
        } else {
            $res = Db::table('ew_user')
                ->where('user_id', session('loginSession')['user_id'])
                ->update(['user_password'=>md5($_POST['password'])]);
            //===========================================
            $data = array();
            $data['remind_whotowho'] = '';
            $data['remind_userid'] = session('loginSession')['user_id'];
            $data['remind_time'] = date('Y-m-d H:i:s');
            $data['remind_type'] = 1;
            $data['remind_ip'] = $_SERVER["REMOTE_ADDR"];
            //===========================================
            if($res){
                $data['remind_status'] = 1;
                Db::table('ew_remind')->insert($data);
                $this->duanxin($admin['user_phone'],3,$admin['user_nickname'],date('H:i'));
                $returnData['status'] = 1;
                $returnData['msg'] = "修改成功";
                return json_encode($returnData);
            }else{
                $data['remind_status'] = 2;
                Db::table('ew_remind')->insert($data);
                $returnData['status'] = 0;
                $returnData['msg'] = "修改失败";
                return json_encode($returnData);
            }
        }
    }
    /**
     * 修改交易密码
     */
    public function deal_userpass()
    {
        return $this->fetch('admin/password');
    }
    public function updatedealPassword()
    {
        $admin = Db::table('ew_user')->where('user_id', session('loginSession')['user_id'])->find();
        if (md5($_POST['oldPassword']) != $admin['user_dealpass']) {
            $returnData['status'] = 0;
            $returnData['msg'] = '原密码输入不正确';
            return json_encode($returnData);
        } else if ($_POST['password'] != $_POST['surePassword']) {
            $returnData['status'] = 0;
            $returnData['msg'] = '两次密码输入不一样';
            return json_encode($returnData);
        } else {
            $res = Db::table('ew_user')
                ->where('user_id', session('loginSession')['user_id'])
                ->update(['user_dealpass'=>md5($_POST['password'])]);
            //===========================================
            $data = array();
            $data['remind_whotowho'] = '';
            $data['remind_userid'] = session('loginSession')['user_id'];
            $data['remind_time'] = date('Y-m-d H:i:s');
            $data['remind_type'] = 2;
            $data['remind_ip'] = $_SERVER["REMOTE_ADDR"];
            //===========================================
            if($res){
                $data['remind_status'] = 1;
                Db::table('ew_remind')->insert($data);
                $this->duanxin($admin['user_phone'],4,$admin['user_nickname'],date('H:i'));
                $returnData['status'] = 1;
                $returnData['msg'] = "修改成功";
                return json_encode($returnData);
            }else{
                $data['remind_status'] = 2;
                Db::table('ew_remind')->insert($data);
                $returnData['status'] = 0;
                $returnData['msg'] = "修改失败";
                return json_encode($returnData);
            }
        }
    }

    /**
     * 修改手机号——1：给旧手机发送验证码
     * 参数：
     * @return string
     */
    public function changephone_old()
    {
        $admin = Db::table('ew_user')->where('user_id', session('loginSession')['user_id'])->find();
        $phone = $admin['user_phone'];
        $one = substr($phone,0,3 );
        $two = substr($phone,7,4 );
        $phone = $one . '****' . $two;
        $this->assign('phone', $phone);
        return $this->fetch("admin/changephone_old");
    }
    /**
     * 修改手机号——2：给旧手机发送验证码
     * 参数：
     * @return string
     */
    public function changephone_old_yzm()
    {
        $res = Db::table('ew_user')->where('user_id', session('loginSession')['user_id'])->find();
        //=============================================================
        $code = md5($_POST['usercode']);
        if($code != $res['user_code']){
            return json_encode(['status'=>0,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['user_codetime'] >= 601){
            return json_encode(['status'=>0,'msg'=>'验证码超时']);
        }
        if($res['user_codestatus'] == 2){
            return json_encode(['status'=>0,'msg'=>'请重新获取验证码']);
        }
        $res2 = Db::table('ew_user')->where('user_id',$res['user_id'])->update(['user_codestatus'=>2]);
        if($res2){
            return json_encode(['status'=>200,'msg'=>'ok']);
        }else{
            return json_encode(['status'=>0,'msg'=>'操作失败，请联系管理员']);
        }

    }
    /**
     * 修改手机号——3：新手机发送验证码
     * 参数：
     * @return string
     */
    public function changephone_new()
    {
        return $this->fetch("admin/changephone_new");
    }
    /**
     * 修改手机号——4：提交新手机
     * 参数：
     * @return string
     */
    public function changephone_new_yzm()
    {
        $phone = trim($_POST['phone'],' ');
        if($phone == ""){
            return json_encode(['status'=>0,'msg'=>'手机号和验证码不能为空']);
        }
        $username = Db::table('ew_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            return json_encode(['status'=>0,'msg'=>'已经有此手机号码用户']);
        }

        $id = session('loginSession')['user_id'];
        $res2 = Db::table('ew_user')->where('user_id',$id)->update(['user_phone'=>$phone]);
        //===========================================
        $data = array();
        $data['remind_whotowho'] = '';
        $data['remind_userid'] = session('loginSession')['user_id'];
        $data['remind_time'] = date('Y-m-d H:i:s');
        $data['remind_type'] = 3;
        $data['remind_ip'] = $_SERVER["REMOTE_ADDR"];
        //===========================================
        if($res2){
            $data['remind_status'] = 1;
            Db::table('ew_remind')->insert($data);
            return json_encode(['status'=>200,'msg'=>'更换成功','phone'=>substr_replace($phone,'****','3','4')]);
        }else{
            $data['remind_status'] = 2;
            Db::table('ew_remind')->insert($data);
            return json_encode(['status'=>0,'msg'=>'更新失败']);
        }

    }
    /**
     * 获得数据
     * Author ghostsf
     * Blog www.ghostsf.com
     */
    public function getDatas()
    {
        set_time_limit(0);
        $rows = $_POST['rows'];
        $page = $_POST['page'];
        $where = array();
        $_POST = $this->getDataByCampusid($_POST);
        $where['user_auth'] = 1;

        $row = Db::table("ew_user")
            ->where($_POST)->where($where)->order('user_createtime desc')
            ->limit($rows * ($page - 1), $rows)->select();
        foreach ($row as $k=>$v){
            $ben = Db::table("ew_contract")->where('con_userid',$v['user_id'])->sum('con_money');
            $fen = Db::table("ew_contract")->where('con_userid',$v['user_id'])->where('con_status',1)->sum('con_allmany');
            $allin_rmb = Db::table('ew_water')
                ->where(['water_userid'=>$v['user_id'],'water_status'=>1,'water_type'=>1,'water_morb'=>1])
                ->sum('water_money');//人民币累计收益============

            //已回款
            $hui = 0;
            $hui_ytb = Db::table('ew_water')
                ->where(['water_userid'=>$v['user_id'],'water_status'=>1,'water_type'=>1,'water_morb'=>2])
                ->field('water_money,water_base')->select();
            if(!empty($hui_ytb)){
                foreach ($hui_ytb as $h){
                    $hui += ($h['water_money']*$h['water_base']);
                }
            }
            $hui = $hui+$allin_rmb;
            $hui = substr(sprintf("%.3f", $hui),0,-1);
            if($hui == 0 || $ben == 0){
                $bili = 0;
            }else{
                $bili = ($hui/$ben)*100;
                $bili = substr(sprintf("%.3f", $bili),0,-1);
            }
            $row[$k]['ben'] = $ben;
            $row[$k]['fen'] = $fen;
            $row[$k]['hui'] = $hui;
            $row[$k]['bili'] = $bili;
        }
        $total = Db::table("ew_user")
            ->where($_POST)->where($where)
            ->count();
        $data['total'] = $total;
        $data['rows'] = $row;
        return json_encode($data);
    }

    public function addadmin()
    {
        return $this->fetch("admin/add");
    }

    public function insert()
    {
        $validata = new AdminValidate();
        if (!$validata->check($_POST)) {
            $returnData['status'] = 0;
            $returnData['msg'] = $validata->getError();
            return json_encode($returnData);
        } else {
            $_POST['user_createtime'] = date("Y-m-d H:i:s");
            $_POST['user_updatetime'] = date("Y-m-d H:i:s");
            $_POST['user_password'] = md5($_POST['user_password']);
            $_POST['user_dealpass'] = md5($_POST['user_dealpass']);
            $ishave = Db::table('ew_user')->where('user_username',$_POST['user_username'])->find();
            $ishave2 = Db::table('ew_user')->where('user_phone',$_POST['user_phone'])->find();
            if(!empty($ishave)){
                $returnData['status'] = 0;
                $returnData['msg'] = "已经有此用户名了";
                return json_encode($returnData);
            }
            if(!empty($ishave2)){
                $returnData['status'] = 0;
                $returnData['msg'] = "已经有此手机号了";
                return json_encode($returnData);
            }
            $res = Db::table('ew_user')->insert($_POST);
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = "成功";
                return json_encode($returnData);
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "保存失败";
                return json_encode($returnData);
            }

        }
    }

    public function updateadmin()
    {
        $id = $_POST['id'];
        $data = Db::table('ew_user')->where('user_id',$id)->find();
        $this->assign('user', $data);
        return $this->fetch("admin/update");
    }

    public function update()
    {
        $id = $_POST['id'];
        unset($_POST['id']);
        $validata = new Admin2Validate();
        if($_POST['user_password'] == ""){
            unset($_POST['user_password']);
        }else{
            if(strlen($_POST['user_password']) < 6){
                return json_encode(['status'=>0,'msg'=>'密码长度不能低于6位']);
            }else{
                $_POST['user_password'] = md5($_POST['user_password']);
            }
        }
        if($_POST['user_dealpass'] == ""){
            unset($_POST['user_dealpass']);
        }else{
            if(strlen($_POST['user_dealpass']) < 6){
                return json_encode(['status'=>0,'msg'=>'密码长度不能低于6位']);
            }else{
                $_POST['user_dealpass'] = md5($_POST['user_dealpass']);
            }
        }
        if (!$validata->check($_POST)) {
            $returnData['status'] = 0;
            $returnData['msg'] = $validata->getError();
            return json_encode($returnData);
        } else {
            $ishave = Db::table('ew_user')->where('user_id',$id)->find();
            if($ishave['user_username'] != $_POST['user_username']){
                $howm = Db::table('ew_user')->where('user_username',$_POST['user_username'])->count();
                if($howm >= 1){
                    return json_encode(['status'=>0,'msg'=>'用户名重复，请重新输入']);
                }
            }
            if($ishave['user_phone'] != $_POST['user_phone']){
                $howm = Db::table('ew_user')->where('user_phone',$_POST['user_phone'])->count();
                if($howm >= 1){
                    return json_encode(['status'=>0,'msg'=>'手机号重复，请重新输入']);
                }
            }
            $_POST['user_rmb'] = substr(sprintf("%.3f", $_POST['user_rmb']),0,-1);
            $_POST['user_ytb'] = substr(sprintf("%.6f", $_POST['user_ytb']),0,-1);
            $_POST['user_updatetime'] = date("Y-m-d H:i:s");
            //=============如果修改了以太币和人民币的话要入流水====================
            $base = Db::table('ew_eth')->find()['eth_price'];
            if($_POST['user_rmb'] > $ishave['user_rmb']){//充值人民币
                $data = array();
                $data['water_userid'] = $id;
                $data['water_money'] = $_POST['user_rmb']-$ishave['user_rmb'];
                $data['water_status'] = 1;
                $data['water_morb'] = 1;
                $data['water_type'] = 6;
                $data['water_out_status'] = 0;
                $data['water_date'] = date("Y-m-d");;
                $data['water_datetime'] = date("Y-m-d H:i:s");
                $data['water_base'] = $base;
                $data['water_usermoney'] = $_POST['user_rmb'];
                $data['water_number'] = 'L' . date('YmdHis') . rand(10000,99999);
                Db::table('ew_water')->insert($data);
            }
            if($_POST['user_rmb'] < $ishave['user_rmb']){//提现人民币
                $data = array();
                $data['water_userid'] = $id;
                $data['water_money'] = $ishave['user_rmb']-$_POST['user_rmb'];
                $data['water_status'] = 2;
                $data['water_morb'] = 1;
                $data['water_type'] = 6;
                $data['water_out_status'] = 1;
                $data['water_date'] = date("Y-m-d");;
                $data['water_datetime'] = date("Y-m-d H:i:s");
                $data['water_base'] = $base;
                $data['water_usermoney'] = $_POST['user_rmb'];
                $data['water_number'] = 'L' . date('YmdHis') . rand(10000,99999);
                Db::table('ew_water')->insert($data);
            }
            if($_POST['user_ytb'] > $ishave['user_ytb']){//充值以太币
                $data = array();
                $data['water_userid'] = $id;
                $data['water_money'] = $_POST['user_ytb']-$ishave['user_ytb'];
                $data['water_status'] = 1;
                $data['water_morb'] = 2;
                $data['water_type'] = 6;
                $data['water_out_status'] = 0;
                $data['water_date'] = date("Y-m-d");;
                $data['water_datetime'] = date("Y-m-d H:i:s");
                $data['water_base'] = $base;
                $data['water_usermoney'] = $_POST['user_ytb'];
                $data['water_number'] = 'L' . date('YmdHis') . rand(10000,99999);
                Db::table('ew_water')->insert($data);
            }
            if($_POST['user_ytb'] < $ishave['user_ytb']){//提现以太币
                $data = array();
                $data['water_us erid'] = $id;
                $data['water_money'] = $ishave['user_ytb']-$_POST['user_ytb'];
                $data['water_status'] = 2;
                $data['water_morb'] = 2;
                $data['water_type'] = 6;
                $data['water_out_status'] = 1;
                $data['water_date'] = date("Y-m-d");;
                $data['water_datetime'] = date("Y-m-d H:i:s");
                $data['water_base'] = $base;
                $data['water_usermoney'] = $_POST['user_ytb'];
                $data['water_number'] = 'L' . date('YmdHis') . rand(10000,99999);
                Db::table('ew_water')->insert($data);
            }
            //====================end=======================================
            $res = Db::table('ew_user')->where('user_id',$id)->update($_POST);
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = "成功";
                return json_encode($returnData);
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "修改失败";
                return json_encode($returnData);
            }
        }
    }

    public function deleteByIDs()
    {
        $ids = input('ids');
        $ids = rtrim($ids, ",");
        $map['id'] = array('in', $ids);
        $deleteinfo = Admin::where($map)->delete();
        if ($deleteinfo) {
            return json_encode(array("status" => 1, "msg" => "删除成功！"));
        } else {
            return json_encode(array("status" => 0, "msg" => "删除失败！"));
        }
    }

    /**
     * @return mixed
     */
    public function ghname()
    {
        $user = Db::name('campus')->where('id=1')->find();
        $this->assign("name", $user['campus_name']);
        $this->assign("id", $user['id']);
        return $this->fetch("admin/dd");
    }

    /**
     * @return string
     * @throws \think\Exception
     */

    public function mark()
    {
        $id = input("id");
        $name = trim(input("name"));

        M("campus")->where(["id" => $id])->update(["campus_name" => $name]);
        return json_encode(["status" => 1, "msg" => '修改成功']);
    }

    /**
     * 公告
     */
    public function gonggao()
    {
        $id = input('id');
        $user = Db::name('notice')->where("id={$id}")->find();
        $this->assign("user", $user);
        return $this->fetch("admin/gonggao");
    }

    /**
     * 公告列表页
     */
    public function gonggaolist()
    {
        $campusid = session("loginSession")['campusid'];
        $num = M("notice")->where(["campusid" => $campusid, "type" => '1', "status" => '1'])->count('id');
        $p=10;
        $max=ceil($num/$p);
        //$_POST
        if(!isset($_POST['p'])) $_POST['p']=1;
        if($_POST['p']<1){$_POST['p']=1;}
        if($_POST['p']>$max){$_POST['P']=$max;}
        $prev=$_POST['p']==1?1:$_POST['p']-1;
        $next=$_POST['p']==$max?$max:$_POST['p']+1;
        $start=($_POST['p']-1)*$p;

        $data = Db::name("notice")->where(["campusid" => $campusid, "type" => '1', "status" => '1'])->order("time desc")->limit("{$start},{$p}")->select();

        $this->assign("datas", $data);
        $this->assign("prev",$prev);
        $this->assign("next",$next);
        $this->assign("max",$max);
        return $this->fetch("admin/list");
    }

    /**
     * 公告列表页
     */

    /**
     * 修补alert
     */
    public function alertlog()
    {
        $ti=input("t");
        if($ti==1){
            $tishi="请选取表格";
        }elseif($ti==2){
            $tishi="导入成功";
        }elseif($ti==3){
            $tishi="只限上传excel表格！";
        }elseif($ti==4){
            $tishi="对不起，选取不能为空";
        }elseif($ti==5){
            $tishi="此功能暂时不对外开放<br/>例子：今天:8点半约张总吃饭";
        }
        $this->assign("ti",$tishi);
        return $this->fetch("admin/alert");
    }
 /**
     * 日历事件页面
     */

    public  function event()
    {
        if($_POST['gd']){
            $_POST['gd']=preg_replace('/GD/',"",$_POST['gd']);
        }
        $user=session("loginSession")['username'];
        $this->assign("user",$user);
        $data=Db::name("event")->where($_POST)->find();
        if($data!=null){
            $this->assign("id",$data['id']);
            $this->assign("content",$data['content']);
            $this->assign("gd",$_POST['gd']);
        }else{
            $this->assign("content","");
            $this->assign("id","");
            $this->assign("gd",$_POST['gd']);
        }

        return $this->fetch("admin/event");
    }

    /**
     * 添加事件  下面是完全版开放内容
     */
    public function addevent()
    {

        if($_POST['id']==null){
            $bool= Db::execute("insert into aew_event (date,day,content,username,gd)values(?,?,?,?,?)",[$_POST['date'],$_POST['day'],$_POST['content'],$_POST['username'],$_POST['gd']]);
            if($bool){
                $data['status']=1;
                $data['msg']="添加成功";

            }else{
                $data['status']=0;
                $data['msg']="添加失败";
            }

            return json_encode($data);
        }else{
            if($_POST["content"]==null){
                $bool=Db::name("event")->where('id',$_POST['id'])->delete();
                if($bool){
                    $data['status']=1;
                    $data['msg']="删除成功";

                }else{
                    $data['status']=0;
                    $data['msg']="删除失败";
                }
                return json_encode($data);
            }else{
                $id=$_POST['id'];
                unset($_POST['id']);
                $bool=Db::name("event")->where(['id'=>$id])->update($_POST);
                if($bool){
                    $data['status']=1;
                    $data['msg']="修改成功";

                }else{
                    $data['status']=0;
                    $data['msg']="修改失败";
                }
                return json_encode($data);
            }
        }

    }

    /** 查询当天有没有事情
     * @return string
     */

    public  function selectEvent()
    {

      $_POST['username']=session("loginSession")['username'];


       $data=Db::name('event')->group("gd")->where($_POST)->field('gd')->select();

        return json_encode($data);
    }


    public function detailEvent()
    {   $_POST['gd']=preg_replace('/GD/',"",$_POST['gd']);
        $_POST['username']=session("loginSession")['username'];
        $data=Db::name("event")->where($_POST)->find();

        $this->assign('data', $data);
        return $this->fetch("admin/details");
    }


}